import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class UserServer {

    private static final String savePath="";
    private ServerSocket server;

    public UserServer(int port) throws IOException {
        this.server=new ServerSocket(port);
    }

    public void start(){
        while(true){
            try {
                Socket userClient = server.accept();
                Message<User> message=MessageUtil.receiveMsg(userClient);
                String action=message.getAction();
                if("register".equals(action)){
                    List<User> users=FileUtil.readData(savePath);
                    //获取注册用户信息
                    User registerUser=message.getData();
                    //检测用户列表中是否存在注册的用户信息
                    boolean exists=users.stream().anyMatch
                            (user->user.equals(registerUser));
                    Message<String> backMsg = new Message<>("back",null);
                    if(exists){
                        backMsg.setData("账号已经被注册");
                    }else{
                        //将用户信息添加至用户列表
                        users.add(registerUser);
                        //将用户信息重新存档
                        boolean result=FileUtil.writeData(savePath,users);
                        String msg=result?"注册成功":"注册失败";
                        backMsg.setData(msg);
                    }
                    MessageUtil.sendMsg(userClient,backMsg);
                }else if("login".equals(action)){
                    User user=message.getData();
                    // 登录逻辑
                }
            }catch(IOException | ClassNotFoundException e){
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        try{
            UserServer server=new UserServer(8888);
            server.start();
        }catch(IOException e){
            e.printStackTrace();
        }
    }
}
